
from rest_framework import exceptions
from rest_framework.permissions import BasePermission
from rest_framework.authentication import BaseAuthentication
import jwt

from api.mylogger import logger


# 解析请求头中的token
def get_tokeninfo(request):
    token = request.META.get("HTTP_TOKEN", "")
    if token == '':
        return {}
    try:
        return jwt.decode(token, verify=False)
    except jwt.exceptions.DecodeError:
        return {}


def get_is_frontend(request):
    endpoint_type = request.META.get("HTTP_ENDPOINTTYPE", '')
    if endpoint_type == 'frontend':
        is_frontend = True
    else:
        is_frontend = False
    return is_frontend


class TokenAuth(BaseAuthentication):
    def authenticate(self, request):

        urlpath = request.path

        if urlpath in ['/api/ping', '/api/member/login', '/api/member/phonelogin', '/api/member/qqlogin',
                       '/api/member/wechatlogin', '/api/user/login', '/api/user/phonelogin', '/api/user/qqlogin',
                       '/api/user/wechatlogin']:
            print('白名单，pass')
            return

        token = request.META.get("HTTP_TOKEN", "")
        if token == '':
            raise exceptions.AuthenticationFailed(detail="请求头中没有带Token", code=401)
        print('token is ', token)

        try:
            token_info = jwt.decode(token, verify=False)
            print('token_info is ', token_info)
        except jwt.exceptions.DecodeError:
            pass
        # 是否在token表中
        # try:
        #     rows = UserToken.objects.filter(token=token)
        #     if len(rows) == 0:
        #         raise exceptions.AuthenticationFailed(detail="Token没有查询到", code=401)
        #     # token_obj = UserTokenSerializer(rows, many=True)[0]
        # except ObjectDoesNotExist:
        #     raise exceptions.AuthenticationFailed(detail="token没有查询到", code=401)

        # 检查token是否过期
        pass

    def authenticate_header(self, request):
        pass


class UserPermission(BasePermission):
    def base_permission_check(self, basename):         # 权限⽩名单
        if basename in ['userinfo', 'permissions', 'login', 'confdict']:
            return True
        else:
            return False

    def has_permission(self, request, view):
        logger.info('UserPermission')
        print("asdfasdfasdfasdf")
        basename = request.path.split('/')[-1]
        print(f"{request.path} basename is {basename}")
        if self.base_permission_check(basename):
            return True

        return True
